package com.libinshen.wxpay.common.util.common;


import com.libinshen.wxpay.common.constant.Constants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Random;

public class JwtUtils {

    //jwt 创建token
    public static String creatToken(Long userId, Date date) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT") // 设置header
                .setHeaderParam("alg", "HS256").setIssuedAt(date) // 设置签发时间
                .setExpiration(new Date(date.getTime() + 1000 * 60 * 60 * 24))
                .claim("userId", String.valueOf(userId)) // 设置内容
                .setIssuer("lbs")// 设置签发人
                .signWith(signatureAlgorithm, Constants.JWT_SECRET); // 签名，需要算法和key

        String jwt = builder.compact();
        return jwt;
    }

    //获取token中的userId
    public static Long getUserId(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(Constants.JWT_SECRET).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = Integer.valueOf(claims.get("userId").toString());
        return userId.longValue();
    }

    //id 生成工具
    public static Long IdUtils() {
        //取当前时间的长整形值包含毫秒
        long millis = System.currentTimeMillis();
        //long millis = System.nanoTime();
        //加上两位随机数
        Random random = new Random();
        int end2 = random.nextInt(99);
        //如果不足两位前面补0
        String str = millis + String.format("%02d", end2);
        long id = new Long(str);
        return id;
    }
}
